const Service = require('egg').Service;
const validateUtil = require('@jianghujs/jianghu/app/common/validateUtil');
const idGenerateUtil = require('@jianghujs/jianghu/app/common/idGenerateUtil');
const { BizError, errorInfoEnum } = require('../constant/error');
const { tableEnum } = require('../constant/constant');
const _ = require('lodash');
const dayjs = require('dayjs');

const actionDataScheme = Object.freeze({
  createTicket: {
    type: 'object',
    additionalProperties: true,
    required: ['ticketBizId', 'ticketType', 'ticketContentRequest'],
    properties: {
      ticketBizId: { anyOf: [{ type: "string" }, { type: "number" }] },
      ticketType: { type: "string", enum: ['保险付款', '保养付款', '发车申请', '退车申请', '发车收款', '退车付款'] },
      ticketContentRequest: { type: 'object' },
      ticketRequestAmount: { anyOf: [{ type: "string" }, { type: "number" }] },
    },
  },


  '保险付款': { type: 'object', },
  '保养付款': { type: 'object', },
  '发车申请': { type: 'object', },
  '退车申请': { type: 'object', },
  '发车收款': { type: 'object', },
  '退车付款': { type: 'object', },
})

class TicketService extends Service {

  // 创建ticket，支持批量
  async createTicket() {
    const { ctx } = this;
    const { jianghuKnex } = this.app;
    const { userId, username } = ctx.userInfo;
    const actionData = this.ctx.request.body.appData.actionData;
    const { dataList } = actionData;

    let idSequence = await this._getIdSequence({ table: 'ticket', startValue: 10001 });
    const insertData = _.map(dataList, item => {
      let { ticketBizId, ticketType, ticketRequestAmount, ticketContentRequest } = item;

      validateUtil.validate(actionDataScheme.createTicket, item);
      validateUtil.validate(actionDataScheme[ticketType], ticketContentRequest, '工单内容');

      const ticket = {
        idSequence,
        ticketId: `T${idSequence}`,
        ticketBizId, ticketType, ticketRequestAmount,
        ticketContentRequest: JSON.stringify(_.omit(ticketContentRequest, ['operation', 'operationByUserId', 'operationByUser', 'operationAt'])),
        ticketRequestAt: dayjs().format(),
        ticketRequestByUserId: userId,
        ticketRequestByUser: username,
      }
      idSequence += 1;

      return ticket;
    })

    await jianghuKnex('ticket', ctx).insert(insertData);
  }

  async _getIdSequence({ table, startValue = 1001 }) {
    const tableName = tableEnum[table];
    const columnName = "idSequence";
    const idSequence = await idGenerateUtil.idPlus({
      knex: this.app.jianghuKnex,
      tableName,
      columnName,
      startValue,
    });
    return idSequence;
  }
}

module.exports = TicketService;